//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================


#include <ddk.h>
#include <stdio.h>
#include <stdlib.h>
#include <osenv.h>
#include <xf86.h>
#include <xf86Priv.h>

extern void  Screen_Init(DisplayModePtr mode);
extern int zee_video_init();

/*
 * Skip all separators, start anywhere
 * Return NULL if string exhausted, else pointer to non-separator
 */
char *SkipBlanks(char *String)
{
    char c;

    if (String == NULL)
        return NULL;

    c = *String;
    while ((c == '\t' || c == ' ') && c != '\0')
        c = *++String;

    return (c == '\0') ? NULL : String;
}

int FindBpp(char *String)
{
    char c,  *q;
    int x = 0;

    q = String;

    c = *q;
    while (c != '\0') {
       if (c == 'x' || c == 'X')
            x++;

        c = *++q;

        if (x == 2) {
             break;
        }
    }

    if (q==NULL) {
        return 0;
    }

    return  atoi(q);
}

DisplayModePtr
zee_video_init_mode(char *modename)
{
    DisplayModePtr modes, p;
    char *name = SkipBlanks(modename);

    if (name == NULL) {
        return NULL;
    }
    xf86bpp = FindBpp(name);

    if ((xf86bpp != 4) && (xf86bpp != 8) && (xf86bpp !=16) &&
        (xf86bpp != 24)&&( xf86bpp != 32)){
        kprintf("Resolution may be 8, 16, 24 or 32\n");
        return NULL;
    }

   if (zee_video_init() != 0 ) {
       kprintf("init s3 video card error, exit\n");
       return NULL;
    }

    p = modes = xf86Screens[0]->modes;

#if 0
    if (x < 0) {
        return NULL;
    }

    while (x && modes->next) {
        modes = modes->next;
        x--;
    }

    if (!p || x) {
        kprintf("zee_video_init_mode: No mode %d!\n", x);
        return NULL;
    }
#endif

    while ( modes->next) {
        if (!strncmp(modes->name, name, strlen(modes->name)))
            break;

       modes = modes->next;
       if (p == modes)
            return NULL;
    }

    if (!modes ) {
        kprintf("zee_video_init_mode: No mode %s!\n",name);
        return NULL;
    }
    Screen_Init(modes);

    return modes;
}


